package net.example.lesson5.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class    ReentrantLockDemo {
    private static ReentrantLock lock = new ReentrantLock();

    /**
     * 无限等待.
     */
    public static void action0(){
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName()+" 获得锁");
            System.out.println(Thread.currentThread().getName()+" 执行Action1");
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }

    /**
     * 限时等待.
     */
    public static void action1(){
        try {
            if(lock.tryLock(5, TimeUnit.SECONDS)){
                System.out.println(Thread.currentThread().getName()+" 执行Action1");
                TimeUnit.SECONDS.sleep(10);
            }else{
                System.out.println(Thread.currentThread().getName()+" 获取锁失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }

    public static void action2(){
        System.out.println(Thread.currentThread().getName()+" 执行Action2");
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new LockTask());
        Thread thread2 = new Thread(new LockTask());
        thread1.start();
        thread2.start();
    }

    static class LockTask implements Runnable{

        @Override
        public void run() {
//            action0();
            action1();
            action2();
        }
    }
}
